package action;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.jdbc.ReturningWork;
import org.hibernate.jdbc.Work;

import bean.User;
import util.HibernateUtil;

public class Query_JDBC {
	public static void main(String[] args) {
		Query_JDBC.jdbc();
	}

	/**
	 * 在Hibernate中获取Connection接口
	 */
	private static void jdbc() {

		Session session = null;
		Transaction tran = null;

		try {

			session = HibernateUtil.getSession();
			tran = session.beginTransaction();

			User user = session.doReturningWork(new ReturningWork<User>() {

				@Override
				public User execute(Connection conn) throws SQLException {
					QueryRunner queryRunner = new QueryRunner();
					String sql = "select username,userid,is_admin as isadmin from user where userid=1";   //数据库中的is_admin和bean中的isdmin不一致
					User user = queryRunner.query(conn, sql,
							new BeanHandler<User>(User.class));

					return user;
				}

			});

			System.out.println("username=" + user.getUsername() + "\t"
					+ "userid=" + user.getUserid() + "\t" + "isadmin?"
					+ user.getIsAdmin());

			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tran.rollback();
		} finally {
			HibernateUtil.closeSession();
		}

	}

}
